

import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, TextInput, Alert, Modal, FlatList, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface AttachmentItem {
  id: string;
  name: string;
  size: string;
  type: 'pdf' | 'docx';
}

interface ProcessNode {
  id: string;
  title: string;
  assignee?: string;
  time: string;
  status: 'completed' | 'active' | 'pending';
}

interface HistoryItem {
  id: string;
  userName: string;
  action: string;
  comment: string;
  time: string;
  status: 'approved' | 'rejected' | 'submitted';
}

const ApprovalDetailScreen = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  
  const [approvalComment, setApprovalComment] = useState('');
  const [isMoreActionsMenuVisible, setIsMoreActionsMenuVisible] = useState(false);

  // 模拟数据
  const approvalData = {
    title: '员工请假申请',
    initiatorName: '李小明',
    initiateTime: '2024-01-15 09:30',
    status: 'pending',
    currentNode: '部门经理审批',
    formData: {
      leaveType: '年假',
      leaveDays: '5天',
      startDate: '2024-01-20',
      endDate: '2024-01-24',
      leaveReason: '春节回家探亲，与家人团聚。已安排好工作交接，期间可通过电话和邮件处理紧急事务。',
      workArrangement: '已将手头工作交接给同事张三，重要事项已记录在共享文档中。',
    },
  };

  const attachments: AttachmentItem[] = [
    {
      id: '1',
      name: '请假申请表.pdf',
      size: '2.3 MB',
      type: 'pdf',
    },
    {
      id: '2',
      name: '工作交接清单.docx',
      size: '1.8 MB',
      type: 'docx',
    },
  ];

  const processNodes: ProcessNode[] = [
    {
      id: '1',
      title: '申请人提交',
      assignee: '李小明',
      time: '2024-01-15 09:30',
      status: 'completed',
    },
    {
      id: '2',
      title: '部门经理审批',
      assignee: '张经理（当前处理人）',
      time: '待处理',
      status: 'active',
    },
    {
      id: '3',
      title: '人力资源审批',
      time: '待处理',
      status: 'pending',
    },
    {
      id: '4',
      title: '审批完成',
      time: '待处理',
      status: 'pending',
    },
  ];

  const historyItems: HistoryItem[] = [
    {
      id: '1',
      userName: '李小明',
      action: '已提交',
      comment: '提交了请假申请',
      time: '2024-01-15 09:30',
      status: 'submitted',
    },
  ];

  const moreActions = [
    { id: 'transfer', title: '转办', icon: 'share-alt' },
    { id: 'add-sign', title: '加签', icon: 'user-plus' },
    { id: 'delegate', title: '委派', icon: 'user-tie' },
    { id: 'back', title: '退回上一步', icon: 'undo' },
    { id: 'cancel', title: '取消', icon: 'ban' },
  ];

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleUrgePress = () => {
    Alert.alert('催办', '确定要催办此审批吗？', [
      { text: '取消', style: 'cancel' },
      { text: '确定', onPress: () => Alert.alert('提示', '催办通知已发送') },
    ]);
  };

  const handleMorePress = () => {
    setIsMoreActionsMenuVisible(!isMoreActionsMenuVisible);
  };

  const handleViewFlowPress = () => {
    const processInstanceId = params.processInstanceId || 'demo-id';
    router.push(`/p-approval_flow?processInstanceId=${processInstanceId}`);
  };

  const handleAttachmentDownload = (attachment: AttachmentItem) => {
    Alert.alert('下载附件', `正在下载 ${attachment.name}`);
  };

  const handleAttachmentView = (attachment: AttachmentItem) => {
    Alert.alert('查看附件', `正在查看 ${attachment.name}`);
  };

  const handleAddAttachmentPress = () => {
    Alert.alert('添加附件', '附件上传功能');
  };

  const handleApprovePress = () => {
    const processInstanceId = params.processInstanceId || 'demo-id';
    router.push(`/p-approval_pass?processInstanceId=${processInstanceId}&comment=${encodeURIComponent(approvalComment)}`);
  };

  const handleRejectPress = () => {
    Alert.alert('驳回', '确定要驳回此审批吗？', [
      { text: '取消', style: 'cancel' },
      {
        text: '确定',
        onPress: () => {
          const processInstanceId = params.processInstanceId || 'demo-id';
          router.push(`/p-approval_process?processInstanceId=${processInstanceId}&action=reject&comment=${encodeURIComponent(approvalComment)}`);
        },
      },
    ]);
  };

  const handleMoreActionPress = (actionId: string) => {
    setIsMoreActionsMenuVisible(false);
    
    switch (actionId) {
      case 'transfer':
        Alert.prompt('转办', '请输入转办人姓名:', (assignee) => {
          if (assignee) {
            Alert.alert('确认转办', `确定要将此审批转办给 ${assignee} 吗？`, [
              { text: '取消', style: 'cancel' },
              {
                text: '确定',
                onPress: () => {
                  const processInstanceId = params.processInstanceId || 'demo-id';
                  router.push(`/p-approval_process?processInstanceId=${processInstanceId}&action=transfer&assignee=${encodeURIComponent(assignee)}&comment=${encodeURIComponent(approvalComment)}`);
                },
              },
            ]);
          }
        });
        break;
      case 'back':
        Alert.alert('退回上一步', '确定要退回上一步吗？', [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
            onPress: () => {
              const processInstanceId = params.processInstanceId || 'demo-id';
              router.push(`/p-approval_process?processInstanceId=${processInstanceId}&action=back&comment=${encodeURIComponent(approvalComment)}`);
            },
          },
        ]);
        break;
      case 'cancel':
        Alert.alert('取消', '确定要取消此审批吗？');
        break;
      default:
        Alert.alert('提示', `${actionId} 功能开发中`);
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '审批中';
      case 'approved':
        return '已通过';
      case 'rejected':
        return '已驳回';
      default:
        return status;
    }
  };

  const getStatusStyle = (status: string) => {
    switch (status) {
      case 'pending':
        return styles.statusPending;
      case 'approved':
        return styles.statusApproved;
      case 'rejected':
        return styles.statusRejected;
      default:
        return styles.statusPending;
    }
  };

  const getNodeIcon = (node: ProcessNode) => {
    switch (node.status) {
      case 'completed':
        return 'check';
      case 'active':
        return 'user';
      default:
        return node.id;
    }
  };

  const getNodeStyle = (status: string) => {
    switch (status) {
      case 'completed':
        return styles.nodeCompleted;
      case 'active':
        return styles.nodeActive;
      default:
        return styles.nodePending;
    }
  };

  const renderAttachmentItem = ({ item }: { item: AttachmentItem }) => (
    <TouchableOpacity
      style={styles.attachmentItem}
      onPress={() => handleAttachmentView(item)}
      activeOpacity={0.7}
    >
      <View style={styles.attachmentInfo}>
        <View style={styles.attachmentIcon}>
          <FontAwesome6
            name={item.type === 'pdf' ? 'file-pdf' : 'file-word'}
            size={20}
            color={item.type === 'pdf' ? '#ef4444' : '#06b6d4'}
          />
        </View>
        <View style={styles.attachmentDetails}>
          <Text style={styles.attachmentName}>{item.name}</Text>
          <Text style={styles.attachmentSize}>{item.size}</Text>
        </View>
      </View>
      <TouchableOpacity
        style={styles.downloadButton}
        onPress={() => handleAttachmentDownload(item)}
        activeOpacity={0.7}
      >
        <FontAwesome6 name="download" size={16} color="#6366f1" />
      </TouchableOpacity>
    </TouchableOpacity>
  );

  const renderProcessNode = ({ item, index }: { item: ProcessNode; index: number }) => (
    <View style={styles.processNode}>
      <View style={[styles.nodeCircle, getNodeStyle(item.status)]}>
        <FontAwesome6
          name={getNodeIcon(item)}
          size={12}
          color={item.status === 'pending' ? '#9ca3af' : '#ffffff'}
        />
      </View>
      {index < processNodes.length - 1 && <View style={styles.nodeLine} />}
      <View style={styles.nodeContent}>
        <Text style={[styles.nodeTitle, item.status === 'pending' && styles.nodeTitlePending]}>
          {item.title}
        </Text>
        <Text style={[styles.nodeAssignee, item.status === 'active' && styles.nodeAssigneeActive]}>
          {item.assignee || '待处理'}
        </Text>
        <Text style={styles.nodeTime}>{item.time}</Text>
      </View>
    </View>
  );

  const renderHistoryItem = ({ item }: { item: HistoryItem }) => (
    <View style={styles.historyItem}>
      <View style={styles.historyIndicator} />
      <View style={styles.historyContent}>
        <View style={styles.historyHeader}>
          <Text style={styles.historyUserName}>{item.userName}</Text>
          <Text style={styles.historyStatus}>{item.action}</Text>
        </View>
        <Text style={styles.historyComment}>{item.comment}</Text>
        <Text style={styles.historyTime}>{item.time}</Text>
      </View>
    </View>
  );

  const renderMoreActionItem = ({ item }: { item: typeof moreActions[0] }) => (
    <TouchableOpacity
      style={styles.moreActionItem}
      onPress={() => handleMoreActionPress(item.id)}
      activeOpacity={0.7}
    >
      <FontAwesome6
        name={item.icon}
        size={16}
        color={item.id === 'cancel' ? '#ef4444' : '#6366f1'}
        style={styles.moreActionIcon}
      />
      <Text style={styles.moreActionText}>{item.title}</Text>
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerLeft}>
          <TouchableOpacity
            style={styles.backButton}
            onPress={handleBackPress}
            activeOpacity={0.7}
          >
            <FontAwesome6 name="arrow-left" size={20} color="#d1d5db" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>审批详情</Text>
        </View>
        <View style={styles.headerRight}>
          <TouchableOpacity
            style={styles.headerButton}
            onPress={handleUrgePress}
            activeOpacity={0.7}
          >
            <FontAwesome6 name="bell" size={20} color="#d1d5db" />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.headerButton}
            onPress={handleMorePress}
            activeOpacity={0.7}
          >
            <FontAwesome6 name="ellipsis-vertical" size={20} color="#d1d5db" />
          </TouchableOpacity>
        </View>
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 审批基本信息 */}
        <View style={styles.section}>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            style={styles.card}
          >
            <View style={styles.approvalHeader}>
              <View style={styles.approvalInfo}>
                <Text style={styles.approvalTitle}>{approvalData.title}</Text>
                <View style={styles.approvalMeta}>
                  <View style={styles.metaItem}>
                    <FontAwesome6 name="user" size={12} color="#6366f1" />
                    <Text style={styles.metaText}>{approvalData.initiatorName}</Text>
                  </View>
                  <View style={styles.metaItem}>
                    <FontAwesome6 name="clock" size={12} color="#6366f1" />
                    <Text style={styles.metaText}>{approvalData.initiateTime}</Text>
                  </View>
                </View>
              </View>
              <View style={[styles.statusBadge, getStatusStyle(approvalData.status)]}>
                <Text style={styles.statusText}>{getStatusText(approvalData.status)}</Text>
              </View>
            </View>

            <View style={styles.currentNode}>
              <View style={styles.currentNodeLeft}>
                <FontAwesome6 name="location-dot" size={14} color="#6366f1" />
                <Text style={styles.currentNodeLabel}>当前节点</Text>
              </View>
              <Text style={styles.currentNodeText}>{approvalData.currentNode}</Text>
            </View>
          </LinearGradient>
        </View>

        {/* 审批表单内容 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>申请内容</Text>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            style={styles.card}
          >
            <View style={styles.formField}>
              <Text style={styles.formLabel}>请假类型</Text>
              <Text style={styles.formValue}>{approvalData.formData.leaveType}</Text>
            </View>
            <View style={styles.formField}>
              <Text style={styles.formLabel}>请假天数</Text>
              <Text style={styles.formValue}>{approvalData.formData.leaveDays}</Text>
            </View>
            <View style={styles.formField}>
              <Text style={styles.formLabel}>开始时间</Text>
              <Text style={styles.formValue}>{approvalData.formData.startDate}</Text>
            </View>
            <View style={styles.formField}>
              <Text style={styles.formLabel}>结束时间</Text>
              <Text style={styles.formValue}>{approvalData.formData.endDate}</Text>
            </View>
            <View style={[styles.formField, styles.formFieldLast]}>
              <Text style={styles.formLabel}>请假事由</Text>
              <Text style={styles.formTextValue}>{approvalData.formData.leaveReason}</Text>
            </View>
            <View style={[styles.formField, styles.formFieldLast]}>
              <Text style={styles.formLabel}>工作安排</Text>
              <Text style={styles.formTextValue}>{approvalData.formData.workArrangement}</Text>
            </View>
          </LinearGradient>
        </View>

        {/* 附件查看 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>附件材料</Text>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            style={styles.card}
          >
            <FlatList
              data={attachments}
              renderItem={renderAttachmentItem}
              keyExtractor={(item) => item.id}
              scrollEnabled={false}
              showsVerticalScrollIndicator={false}
            />
          </LinearGradient>
        </View>

        {/* 审批流程进度 */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>审批流程</Text>
            <TouchableOpacity
              style={styles.viewFlowButton}
              onPress={handleViewFlowPress}
              activeOpacity={0.7}
            >
              <Text style={styles.viewFlowText}>查看流程图</Text>
              <FontAwesome6 name="external-link" size={12} color="#6366f1" />
            </TouchableOpacity>
          </View>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            style={styles.card}
          >
            <FlatList
              data={processNodes}
              renderItem={renderProcessNode}
              keyExtractor={(item) => item.id}
              scrollEnabled={false}
              showsVerticalScrollIndicator={false}
            />
          </LinearGradient>
        </View>

        {/* 历史审批记录 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>审批记录</Text>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            style={styles.card}
          >
            <FlatList
              data={historyItems}
              renderItem={renderHistoryItem}
              keyExtractor={(item) => item.id}
              scrollEnabled={false}
              showsVerticalScrollIndicator={false}
            />
          </LinearGradient>
        </View>

        {/* 审批操作区 */}
        <View style={styles.section}>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            style={styles.card}
          >
            <View style={styles.approvalActions}>
              <Text style={styles.commentLabel}>审批意见</Text>
              <TextInput
                style={styles.commentInput}
                value={approvalComment}
                onChangeText={setApprovalComment}
                placeholder="请输入您的审批意见..."
                placeholderTextColor="#9ca3af"
                multiline
                numberOfLines={3}
                textAlignVertical="top"
              />

              <TouchableOpacity
                style={styles.addAttachmentButton}
                onPress={handleAddAttachmentPress}
                activeOpacity={0.7}
              >
                <FontAwesome6 name="paperclip" size={16} color="#6366f1" />
                <Text style={styles.addAttachmentText}>添加附件/备注</Text>
              </TouchableOpacity>
            </View>
          </LinearGradient>
        </View>

        {/* 底部间距 */}
        <View style={styles.bottomSpacing} />
      </ScrollView>

      {/* 底部固定操作栏 */}
      <View style={styles.bottomActionBar}>
        <TouchableOpacity
          style={styles.rejectButton}
          onPress={handleRejectPress}
          activeOpacity={0.8}
        >
          <FontAwesome6 name="xmark" size={16} color="#ffffff" />
          <Text style={styles.rejectButtonText}>拒绝</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.approveButton}
          onPress={handleApprovePress}
          activeOpacity={0.8}
        >
          <LinearGradient
            colors={['#6366f1', '#8b5cf6']}
            style={styles.approveButtonGradient}
          >
            <FontAwesome6 name="check" size={16} color="#ffffff" />
            <Text style={styles.approveButtonText}>通过</Text>
          </LinearGradient>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.moreActionsButton}
          onPress={handleMorePress}
          activeOpacity={0.8}
        >
          <FontAwesome6 name="ellipsis" size={16} color="#ffffff" />
        </TouchableOpacity>
      </View>

      {/* 更多操作弹出菜单 */}
      <Modal
        visible={isMoreActionsMenuVisible}
        transparent
        animationType="fade"
        onRequestClose={() => setIsMoreActionsMenuVisible(false)}
      >
        <TouchableOpacity
          style={styles.modalOverlay}
          activeOpacity={1}
          onPress={() => setIsMoreActionsMenuVisible(false)}
        >
          <View style={styles.moreActionsMenu}>
            <FlatList
              data={moreActions}
              renderItem={renderMoreActionItem}
              keyExtractor={(item) => item.id}
              scrollEnabled={false}
              showsVerticalScrollIndicator={false}
            />
          </View>
        </TouchableOpacity>
      </Modal>
    </SafeAreaView>
  );
};

export default ApprovalDetailScreen;

